<!--
 * @Author: C.
 * @Date: 2023-03-07 11:18:13
-->
<template>
  <BasicModal v-bind="$attrs" @register="registerModal" @ok="handleSubmit">
    <BasicForm @register="register" />
  </BasicModal>
</template>
<script lang="ts" setup name="FormModel">
  import { ref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { BasicModal, useModalInner } from '/@/components/Modal';

  const emit = defineEmits(['success', 'register']);

  const [registerForm, formActions] = useForm();
  // 设置默认参数
  const initProps = ref({
    schemas: [],
    labelWidth: 100,
    baseColProps: { span: 24 },
    showActionButtonGroup: false,
  });
  const [registerModal, modelActions] = useModalInner((data) => {
    if (data?.init) {
      Object.assign(initProps.value, data);
    }

    if (Reflect.has(data, 'formData')) {
      // console.log(data.formData);
      formActions.resetFields();
      formActions.setFieldsValue(data.formData);
    }

    modelActions.setModalProps({ confirmLoading: false });
  });
  function register(instance) {
    registerForm(instance);
    initProps.value && formActions.setProps(initProps.value);
  }
  async function handleSubmit() {
    try {
      modelActions.setModalProps({ confirmLoading: true });
      await formActions.validateFields();
      const formData = formActions.getFieldsValue();
      console.log(formData);

      emit('success', formData);
      modelActions.closeModal();
    } finally {
      modelActions.setModalProps({ confirmLoading: false });
    }
  }
</script>
